import { defineStore } from 'pinia'

// 定义一个 Pinia 状态管理器，名为 'system'
const useSystemStore = defineStore('system', {
    state: () => {
        return {
            // 是否为移动设备
            isMobile: false as boolean,
            // 网站信息
            website: {} as Record<string, any>,
            // 布局设置
            layout: {} as Record<string, any>,
            // 版权信息
            copyright: {} as Record<string, any>,
            // 登录配置
            login: {} as Record<string, any>,
            // 应用配置
            app: {} as Record<string, any>,
            // 未读消息数量
            unread: 0 as number,
        }
    },
    actions: {
        // 设置是否为移动设备
        setIsMobile(key: boolean) {
            this.isMobile = key
        },
        // 设置主题布局
        setTheme(key: string) {
            this.layout.theme = key
        },
        // 切换暗模式
        toggleDark() {
            this.layout.dark = !this.layout.dark
        },
        // 切换菜单折叠状态
        toggleMenuIsCollapse() {
            this.layout.menuIsCollapse = !this.layout.menuIsCollapse
        },
        // 切换布局标签
        toggleLayoutTags() {
            this.layout.layoutTags = !this.layout.layoutTags
        },
        // 异步设置语言
        async setLang(value: string) {
            try {
                const lang = await api.system.websetlang.put({ id: 0, key: 'LAYOUT_SETTING', lang: value })
                if (lang.code === 200) {
                    this.layout.lang = value
                    lang.global.locale = this.layout.lang
                    tool.cookie.set('lang', value, { path: '/' })
                }
            } catch (error) {
                console.error('Error setting language:', error)
            }
        },
        // 获取网站配置
        async getSite() {
            try {
                const site = await api.system.website.get()
                if (site.code === 200) {
                    this.website = site.data
                }
            } catch (error) {
                console.error('Error fetching site configuration:', error)
            }
        },
        // 获取系统配置
        async getConfig() {
            try {
                const config = await api.system.webconfig.get({ id: 0, key: 'APP_CONFIG,LAYOUT_SETTING,COPYRIGHT,LOGIN_CONFIG' })
                if (config.code === 200) {
                    this.layout = config.data.layout_setting
                    this.copyright = config.data.copyright
                    this.login = config.data.login_config
                    this.app = config.data.app_config
                    this.unread = config.data.unread
                }
            } catch (error) {
                console.error('Error fetching system configuration:', error)
            }
        },
    }
})

// 导出定义的 store 以供使用
export default useSystemStore